<template>
  <div class="page-platform-report">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="version"
            label="版本号:"
          >
            <el-input
              v-model="searchForm.version"
              type="text"
              clearable
              placeholder="版本号"
            />
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm('searchForm')"
            >
              重置
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="operation-bar">
        <div
          class="default-btn primary-btn"
          @click.stop="onAddOrUpdate()"
        >
          {{ $t("sysManagement.add") }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            label="版本号"
            prop="version"
            show-overflow-tooltip
          />

          <el-table-column
            label="创建时间"
            prop="createdTime"
            show-overflow-tooltip
          />

          <el-table-column
            label="发布时间"
            prop="publishTime"
            show-overflow-tooltip
          />

          <el-table-column
            label="状态"
            prop="status"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.status == 1 ? '已发布' : '未发布' }}
            </template>
          </el-table-column>

          <el-table-column
            label="更新日志"
            prop="updateLog"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ getText(scope.row.updateLog || '') }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="200"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  class="default-btn text-btn"
                  @click="onPublish(scope.row)"
                >
                  {{ scope.row.status == 1 ? '取消发布' : '发布' }}
                </div>

                <div
                  class="default-btn text-btn"
                  @click="onDownload(scope.row)"
                >
                  下载
                </div>

                <div
                  v-if="scope.row.status != 1"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.id)"
                >
                  编辑
                </div>

                <div
                  v-if="scope.row.status != 1"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.id)"
                >
                  {{ $t("text.delBtn") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment'

const getText = (str) => {
  return str ? str.replace(/<[^<>]+>/g, '').replace(/&nbsp;/gi, '') : ''
}

// 修改
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({})

onMounted(() => {
  getDataList(page)
})

// 获取数据列表
const dataList = ref([])
let tempSearchForm = null // 保存上次点击查询的请求条件
const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/shop/pluginVersion/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total

    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

// 新增 / 修改
const addOrUpdateRef = ref(null)
const addOrUpdateVisible = ref(false)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}

const onDelete = (id) => {
  ElMessageBox.confirm('确认删除吗?', {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/shop/pluginVersion/${id}`),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      ElMessage({
        message: $t('remindPop.succeeded'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}

const onPublish = ({ id, status }) => {
  ElMessageBox.confirm('确认执行此操作吗?', {
    confirmButtonText: $t('remindPop.confirm'),
    cancelButtonText: $t('remindPop.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/shop/pluginVersion'),
      method: 'put',
      data: http.adornData({
        id,
        status: status == 0 ? 1 : 0,
        publishTime: status == 0 ? moment(new Date()).format('YYYY-MM-DD HH:mm:ss') : null
      })
    }).then(() => {
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
}

const onDownload2 = (item) => {
  const fixxed = item.filePath.slice(item.filePath.lastIndexOf('.'))
  const uri = new URL(checkFileUrl(item.filePath))
  uri.searchParams.set('response-content-type', 'application/octet-stream') // 避免文件变成预览
  const link = document.createElement('a')
  link.href = uri.toString()
  link.download = item.version + fixxed
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const onDownload = (item) => {
  const fixxed = item.filePath.slice(item.filePath.lastIndexOf('.'))
  const xml = new XMLHttpRequest()
  xml.open('GET', checkFileUrl(item.filePath), true)
  xml.responseType = 'blob'
  xml.onload = function () {
    const url = window.URL.createObjectURL(xml.response)
    const a = document.createElement('a')
    a.href = url
    a.download = 'YIDAOForSWInstaller_' + item.version + fixxed
    a.click()
  }
  xml.send()
}

const onDownload1 = (doc) => {
  const fileName = doc.version
  const elink = document.createElement('a')
  elink.style.display = 'none'
  elink.href = checkFileUrl(doc.filePath)
  elink.download = fileName
  document.body.appendChild(elink)
  elink.click()
  URL.revokeObjectURL(elink.href) // 释放URL 对象
  document.body.removeChild(elink)
}

// 条件查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}
// 刷新回调
const refreshChange = () => {
  getDataList(page)
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}

const searchFormRef = ref(null)
const resetForm = () => {
  searchFormRef.value.resetFields()
}
</script>
